package com.lebang.service;

import com.lebang.configuration.datasource.DataSource;
import com.lebang.domain.AllTaskWorthRecord;
import com.lebang.example.AllTaskWorthRecordExample;
import com.lebang.mapper.AllTaskWorthRecordMapper;
import com.lebang.model.MyConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;

/**
 * 总任务价值录制
 *
 * @Author xwj
 * @Date 2020-09-18
 */
@Service
@Slf4j
public class AllTaskWorthRecordService extends BaseService<AllTaskWorthRecord, Integer, AllTaskWorthRecordExample> {

    @Autowired
    private AllTaskWorthRecordMapper allTaskWorthRecordMapper;


    /**
     * 检查当前应用录入日期指定数据源是否存在
     * @param vo
     * @return
     */
    public boolean checkExit(AllTaskWorthRecord vo) {
        Integer isExit = allTaskWorthRecordMapper.selectByTimeSdk(vo.getAppid(),vo.getTime(),vo.getSdkKey());
        if(isExit!=null){
            return true;
        }
        return false;
    }

    @DataSource("commonDB")
    public void update(AllTaskWorthRecord vo) {
        allTaskWorthRecordMapper.updateByPrimaryKeySelective(vo);
    }

    @DataSource("commonDB")
    public void insert(AllTaskWorthRecord vo) {
        allTaskWorthRecordMapper.insertSelective(vo);
    }

    public AllTaskWorthRecord checkData(AllTaskWorthRecord vo) {
        //4.4CPM：收益/展示*1000（保留两位小数点）
        vo.setCpm(vo.getAward().multiply(BigDecimal.valueOf(1000)).divide(BigDecimal.valueOf(vo.getShow()),2,BigDecimal.ROUND_DOWN));
    return vo;

    }

    /**
     * 初始化参数
     * @param recordList
     * @return
     */
    public List<AllTaskWorthRecord> calculationAllRecord(List<AllTaskWorthRecord> recordList) {
        recordList.forEach(s->{
            //4.4CPM：收益/展示*1000（保留两位小数点）
            s.setCpm(s.getAward().multiply(BigDecimal.valueOf(1000)).divide(BigDecimal.valueOf(s.getShow()),2,BigDecimal.ROUND_DOWN));
        });
        return recordList;
    }

    /**
     * 批量写入数据
     * @param recordList
     */
    @DataSource("commonDB")
    public void insertList(List<AllTaskWorthRecord> recordList) {
        LocalDate now = LocalDate.now();
        recordList.forEach(s->{
            s.setCreateTime(now);
            s.setAppid(MyConfig.getEnv());
            allTaskWorthRecordMapper.insertSelective(s);
        });
    }
}
